package auth

import (
	"gin_demo/jwt"
	v "gin_demo/validator"
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	"go.uber.org/zap"
	"net/http"
)

// binding from json
type UserInfo struct {
	Username string `json:"username" form:"username" binding:"required"`
	Password string `json:"password" form:"password" binding:"required"`
}

func authHandler(c *gin.Context) {
	zap.L().Debug("trying to login")
	var user UserInfo
	if err := c.ShouldBind(&user); err != nil {
		errs, ok := err.(validator.ValidationErrors)
		if !ok {
			c.JSON(http.StatusBadRequest, gin.H{
				"msg": err.Error(),
			})
			return
		}
		// validator.ValidationErrors类型错误则进行翻译
		c.JSON(http.StatusOK, gin.H{
			"msg": errs.Translate(v.Trans),
		})
		return
	}
	if user.Username == "admin" && user.Password == "123456" {
		zap.L().Debug("username", zap.String("username", user.Username))
		tokenString, _ := jwt.GenToken(user.Username)
		c.JSON(http.StatusOK, gin.H{
			"data": gin.H{
				"token": tokenString,
			},
		})
		return
	}
	c.JSON(http.StatusUnauthorized, gin.H{
		"msg": "failed",
	})
	return
}
